package dk.ucn.rejsealarmen;

import java.util.ArrayList;
import java.util.HashMap;

import tools.TripParser;
import android.app.ListActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class ActivityPage2 extends ListActivity {

	private static final String TAG = "ActivityPage2";
	private static final String TAG2 = "AsyncTaskP2";

	String originName = null;
	int originX = 0;
	int originY = 0;
	int originId = 0;
	String originType = null;

	String destName = null;
	int destX = 0;
	int destY = 0;
	int destId = 0;
	String destType = null;

	String date = null;
	String time = null;

	String useBus = null;
	String useTrain = null;
	String useMetro = null;

	Button button_earlier_trips;
	Button button_later_trips;

	ArrayList<ArrayList<HashMap<String, String>>> tripList;
	TripParser tripParser;

	TextView tvDate;
	TextView tripIdTextView;
	private String baseUrl;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_page2);
		Log.d(TAG, "Page2 onCreate called");
		tripParser = new TripParser();

		// Show the Up button in the action bar.
		setupActionBar();
		tripList = new ArrayList<ArrayList<HashMap<String, String>>>();

		baseUrl = (String) getText(R.string.baseUrl);

		button_earlier_trips = (Button) findViewById(R.id.button_earlier_trips);
		button_later_trips = (Button) findViewById(R.id.button_later_trips);
		tvDate = (TextView) findViewById(R.id.tv_date);

		savedInstanceState = getIntent().getExtras();
		final String myUrl = setupUrl(savedInstanceState);

		new MyAsyncTask().execute(myUrl);
	}

	private ArrayList<HashMap<String, String>> getTripInfo(int tripId) {
		ArrayList<HashMap<String, String>> myTripList = new ArrayList<HashMap<String, String>>();
		for (int i = 0; i < tripList.size(); i++) {
			for (int j = 0; j < tripList.get(i).size(); j++) {
				if (Integer.parseInt(tripList.get(i).get(j).get("tripId")) == tripId) {
					HashMap<String, String> tripMap = new HashMap<String, String>();
					tripMap.put("tripId", String.valueOf(tripId));
					tripMap.put("legId", tripList.get(i).get(j).get("legId"));
					tripMap.put("legName", tripList.get(i).get(j)
							.get("legName"));
					tripMap.put("legType", tripList.get(i).get(j)
							.get("legType"));
					tripMap.put("originName",
							tripList.get(i).get(j).get("originName"));
					tripMap.put("originType",
							tripList.get(i).get(j).get("originType"));
					tripMap.put("originTime",
							tripList.get(i).get(j).get("originTime"));
					tripMap.put("originDate",
							tripList.get(i).get(j).get("originDate"));
					tripMap.put("destinationName",
							tripList.get(i).get(j).get("destinationName"));
					tripMap.put("destinationType",
							tripList.get(i).get(j).get("destinationType"));
					tripMap.put("destinationTime",
							tripList.get(i).get(j).get("destinationTime"));
					tripMap.put("destinationDate",
							tripList.get(i).get(j).get("destinationDate"));
					tripMap.put("notesText",
							tripList.get(i).get(j).get("notesText"));
					try {
						tripMap.put("journeyDetailRef", tripList.get(i).get(j)
								.get("journeyDetailRef"));
					} catch (Exception e) {
						e.printStackTrace();
					}
					myTripList.add(tripMap);
				}
			}

		}
		return myTripList;
	}

	private class MyAsyncTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			tripList = tripParser.getTripList(params[0]);
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			ArrayList<HashMap<String, String>> myTripList = new ArrayList<HashMap<String, String>>();
			for (int i = 0; i < tripList.size(); i++) {
				Log.d(TAG2,
						"********************************************************************");
				Log.d(TAG2,
						"********************************************************************");
				Log.d(TAG2, "Triplist size: " + tripList.size());
				Log.d(TAG2, "Trip id: = "
						+ tripList.get(i).get(0).get("tripId"));

				String tripId = tripList.get(i).get(0).get("tripId");

				boolean found = false;
				int j = 0;
				while (!found) {
					if (!tripList.get(i).get(j).get("legName")
							.equals("til fods")) {
						Log.d(TAG2,
								"Trip id: = "
										+ tripList.get(i).get(j).get("tripId"));

						Log.d(TAG2,
								"Leg id: = "
										+ tripList.get(i).get(j).get("legId"));
						Log.d(TAG2, tripList.get(i).get(j).get("legName"));
						Log.d(TAG2, tripList.get(i).get(j).get("legType"));
						Log.d(TAG2, tripList.get(i).get(j).get("originName"));
						Log.d(TAG2, tripList.get(i).get(j).get("originType"));
						Log.d(TAG2, tripList.get(i).get(j).get("originTime"));
						Log.d(TAG2, tripList.get(i).get(j).get("originDate"));
						Log.d(TAG2,
								tripList.get(i).get(j).get("destinationName"));
						Log.d(TAG2,
								tripList.get(i).get(j).get("destinationType"));
						Log.d(TAG2,
								tripList.get(i).get(j).get("destinationTime"));
						Log.d(TAG2,
								tripList.get(i).get(j).get("destinationDate"));
						Log.d(TAG2, tripList.get(i).get(j).get("notesText"));
						try {
							Log.d(TAG2,
									tripList.get(i).get(j)
											.get("journeyDetailRef"));
						} catch (Exception e) {
							Log.d(TAG2, "JourneyDetailRef er tom");
						}
						Log.d(TAG2, "**********************************");

						HashMap<String, String> tripMap = new HashMap<String, String>();
						tripMap.put("tripId", tripId);
						tripMap.put("legId", tripList.get(i).get(j)
								.get("legId"));
						tripMap.put("legName",
								tripList.get(i).get(j).get("legName"));
						tripMap.put("legType",
								tripList.get(i).get(j).get("legType"));
						tripMap.put("originName",
								tripList.get(i).get(j).get("originName"));
						tripMap.put("originType",
								tripList.get(i).get(j).get("originType"));
						tripMap.put("originTime",
								tripList.get(i).get(j).get("originTime"));
						tripMap.put("originDate",
								tripList.get(i).get(j).get("originDate"));
						tripMap.put("destinationName", tripList.get(i).get(j)
								.get("destinationName"));
						tripMap.put("destinationType", tripList.get(i).get(j)
								.get("destinationType"));
						tripMap.put("destinationTime", tripList.get(i).get(j)
								.get("destinationTime"));
						tripMap.put("destinationDate", tripList.get(i).get(j)
								.get("destinationDate"));
						tripMap.put("notesText",
								tripList.get(i).get(j).get("notesText"));
						try {
							tripMap.put("journeyDetailRef", tripList.get(i)
									.get(j).get("journeyDetailRef"));
						} catch (Exception e) {
							e.printStackTrace();
						}
						myTripList.add(tripMap);
						found = true;
					} else {
						j++;
					}
				}

			}

			ListAdapter adapter = new SimpleAdapter(getApplicationContext(),
					myTripList, R.layout.trip_entry, new String[] { "tripId",
							"legName", "originTime", "destinationTime" },
					new int[] { R.id.tripIdTextView,
							R.id.transportNameTextView, R.id.departureTextView,
							R.id.arrivalTextView });
			setListAdapter(adapter);
			
		}

	}

	private String setupUrl(Bundle savedInstanceState) {
		String myUrl;
		String tempUrl = baseUrl + getString(R.string.trip_feed);

		// Get data fra originLocation
		try {
			originName = savedInstanceState.getString("originCoordName");
			Log.d(TAG, "OriginName: " + originName);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			originType = savedInstanceState.getString("originLocationType");
			Log.d(TAG, "OriginType: " + originType);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			originX = savedInstanceState.getInt("originCoordX");
			Log.d(TAG, "originX: " + originX);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			originY = savedInstanceState.getInt("originCoordY");
			Log.d(TAG, "originY: " + originY);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			originId = savedInstanceState.getInt("originId");
			Log.d(TAG, "originId: " + originId);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// Get data fra destLocation
		try {
			destName = savedInstanceState.getString("destCoordName");
			Log.d(TAG, "destName: " + destName);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			destType = savedInstanceState.getString("destinationLocationType");
			Log.d(TAG, "destType: " + destType);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			destX = savedInstanceState.getInt("destCoordX");
			Log.d(TAG, "destX: " + destX);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			destY = savedInstanceState.getInt("destCoordY");
			Log.d(TAG, "destY: " + destY);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			destId = savedInstanceState.getInt("destCoordId");
			Log.d(TAG, "destId: " + destId);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// Get date and time

		try {
			time = savedInstanceState.getString("time");
			Log.d(TAG, "time: " + time);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			date = savedInstanceState.getString("date");
			Log.d(TAG, "date: " + date);
			tvDate.setText(date);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// Get data from chosen transport method

		try {
			useBus = savedInstanceState.getString("useBus");
			Log.d(TAG, "useBus: " + useBus);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			useTrain = savedInstanceState.getString("useTog");
			Log.d(TAG, "useTog: " + useTrain);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			useMetro = savedInstanceState.getString("useMetro");
			Log.d(TAG, "useMetro: " + useMetro);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (originId != 0) {
			if (destId != 0) {
				// http://<baseurl>/trip?originId=8600626&destId=<xInteger>&useBus=0
				tempUrl = tempUrl + "originId=" + originId + "&destId="
						+ destId + "&date=" + date + "&time=" + time
						+ "&useBus=" + useBus + "&useTog=" + useTrain
						+ "&useMetro=" + useMetro;
			} else {
				// http://<baseurl>/trip?originId=8600626&destCoordX=<xInteger>&destCoordY=<yInteger>&destCoordName=<NameOfDestination>&useBus=0
				tempUrl = tempUrl + "originId=" + originId + "&destCoordX="
						+ destX + "&destCoordY=" + destY + "&destCoordName="
						+ destName + "&date=" + date + "&time=" + time
						+ "&useBus=" + useBus + "&useTog=" + useTrain
						+ "&useMetro=" + useMetro;
			}
		} else {
			if (destId != 0) {
				// http://<baseurl>/trip?originCoordX=<Integer>&originCoordY=<Integer>&originCoordName=<NameOfOrigin>&destId=<Integer>
				tempUrl = tempUrl + "originCoordX=" + originX
						+ "&originCoordY=" + originY + "&originCoordName="
						+ originName + "&destId=" + destId + "&date=" + date
						+ "&time=" + time + "&useBus=" + useBus + "&useTog="
						+ useTrain + "&useMetro=" + useMetro;
			} else {
				// http://<baseurl>/trip?originCoordX=<Integer>&originCoordY=<Integer>&originCoordName=<NameOfOrigin>&destCoordX=<xInteger>&destCoordY=<yInteger>&destCoordName=<NameOfDestination>&useBus=0
				tempUrl = tempUrl + "originCoordX=" + originX
						+ "&originCoordY=" + originY + "&originCoordName="
						+ originName + "&destCoordX=" + destX + "&destCoordY="
						+ destY + "&destCoordName=" + destName + "&date="
						+ date + "&time=" + time + "&useBus=" + useBus
						+ "&useTog=" + useTrain + "&useMetro=" + useMetro;
			}
		}
		tempUrl = tempUrl.replaceAll(" ", "%20");
		myUrl = tempUrl;
		return myUrl;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		tripIdTextView = (TextView) v.findViewById(R.id.tripIdTextView);
		int tripIdTextViewValue = Integer.parseInt(tripIdTextView.getText()
				.toString());

		ArrayList<HashMap<String, String>> myTripList = getTripInfo(tripIdTextViewValue);
		Log.d("onListItemClick", "Number of Legs: " + myTripList.size());
		Intent intent = new Intent(this.getApplicationContext(),
				ActivityPage3.class);
		for (int i = 0; i < myTripList.size(); i++) {
			intent.putExtra("legId" + String.valueOf(i), i);
			intent.putExtra("legName" + String.valueOf(i), myTripList.get(i).get("legName"));
			intent.putExtra("legType" + String.valueOf(i), myTripList.get(i).get("legType"));
			intent.putExtra("originName" + String.valueOf(i), myTripList.get(i).get("originName"));
			intent.putExtra("originType" + String.valueOf(i), myTripList.get(i).get("originType"));
			intent.putExtra("originTime" + String.valueOf(i), myTripList.get(i).get("originTime"));
			intent.putExtra("originDate" + String.valueOf(i), myTripList.get(i).get("originDate"));
			intent.putExtra("destinationName" + String.valueOf(i), myTripList.get(i).get("destinationName"));
			intent.putExtra("destinationType" + String.valueOf(i), myTripList.get(i).get("destinationType"));
			intent.putExtra("destinationTime" + String.valueOf(i), myTripList.get(i).get("destinationTime"));
			intent.putExtra("destinationDate" + String.valueOf(i), myTripList.get(i).get("destinationDate"));
			intent.putExtra("notesText" + String.valueOf(i), myTripList.get(i).get("notesText"));

			try {
				intent.putExtra("journeyDetailRef" + String.valueOf(i), myTripList.get(i).get("journeyDetailRef"));
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			Log.d("onListItemClick", "Leg id: " + i);
			Log.d("onListItemClick", myTripList.get(i).get("legName"));
			Log.d("onListItemClick", myTripList.get(i).get("legType"));
			Log.d("onListItemClick", myTripList.get(i).get("originName"));
			Log.d("onListItemClick", myTripList.get(i).get("originType"));
			Log.d("onListItemClick", myTripList.get(i).get("originTime"));
			Log.d("onListItemClick", myTripList.get(i).get("originDate"));
			Log.d("onListItemClick", myTripList.get(i).get("destinationName"));
			Log.d("onListItemClick", myTripList.get(i).get("destinationType"));
			Log.d("onListItemClick", myTripList.get(i).get("destinationTime"));
			Log.d("onListItemClick", myTripList.get(i).get("destinationDate"));
			Log.d("onListItemClick", myTripList.get(i).get("notesText"));

			try {
				Log.d("onListItemClick",
						myTripList.get(i).get("journeyDetailRef"));
			} catch (Exception e) {
				Log.d("onListItemClick", "journeyDetailRef is empty");
			}
			intent.putExtra("numberOfLegs", myTripList.size());
			Log.d("onListItemClick", "*************************************");
			startActivity(intent);
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.page2, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * Set up the {@link android.app.ActionBar}.
	 */

	private void setupActionBar() {

		getActionBar().setDisplayHomeAsUpEnabled(true);

	}

}
